package com.zues.thread.design_mode.ending;

import com.zues.thread.util.ThreadUtil;

/**
 * 演示终止模式
 * 终止模式之两阶段终止模式：停止标记用volatile是为了保证该变量的在多个线程之间的可见性
 * @author zues
 * @date 3/11/2025 8:54 下午
 */
public class TwoPhaseTermination {

    //监控线程
    private Thread monitor;

    //停止标记
    private volatile boolean stop = false;

    public void start(){

        monitor = new Thread(()->{
            while(true){
                Thread thread = Thread.currentThread();
                if(stop){
                    System.out.println("后置处理");
                    break;
                }
                try {
                    Thread.sleep(1000);//睡眠
                    System.out.println(thread.getName() + "执行监控记录");
                } catch (InterruptedException e) {
                    System.out.println("被打断，退出睡眠");
                }
            }
        });
        monitor.start();
    }


    public void stop(){
        stop = true;
        monitor.interrupt();
    }


    public static void main(String[] args) {
        TwoPhaseTermination tpt = new TwoPhaseTermination();
        tpt.start();
        ThreadUtil.sleep(5);
        System.out.println("停止监控");
        tpt.stop();
    }

}
